package com.ask.interceptor;

import com.ask.constant.JwtClaimsConstant;
import com.ask.context.BaseContext;
import com.ask.properties.JwtProperties;
import com.ask.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;


@Slf4j
@Component

public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是控制器方法，直接放行
            return true;
        }

        // 1. 从请求头中获取JWT令牌
        String accessToken = request.getHeader(jwtProperties.getAccessTokenName());
        if (accessToken == null || accessToken.isEmpty()) {
            response.setStatus(401);
            return false;
        }


        // 2. 校验JWT令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), accessToken);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            BaseContext.setCurrentId(empId);
            return true;
        } catch (ExpiredJwtException e) { //Access Token 过期, 校验refreshToken
            String storedRefreshToken = stringRedisTemplate.opsForValue().get(accessToken);
            if (storedRefreshToken == null || storedRefreshToken.isEmpty()) {
                return false;
            }

            try { // 解析refreshToken
                Claims claims = JwtUtil.parseJWT(jwtProperties.getRefreshSecretKey(), storedRefreshToken);
                Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
                BaseContext.setCurrentId(empId);

                // 生成新的AccessToken
                String new_accessToken = JwtUtil.createJWT(
                        jwtProperties.getAdminSecretKey(),
                        jwtProperties.getAdminTtl(),
                        claims);

                // 将新的 Access Token 写入响应头
                response.setHeader(jwtProperties.getAccessTokenName(), new_accessToken);
                return true;
            } catch (Exception e1) { // RefreshToken 校验失败
                return false;
            }

        } catch (Exception e) {
            return false;
        }
    }

    private String getToken(HttpServletRequest request, String tokenName) {
        // 获取所有 Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("user_info".equals(cookie.getName())) {
                    try {
                        // URL 解码
                        String decodedValue = URLDecoder.decode(cookie.getValue(), "UTF-8");
                        // 解析 JSON
                        JSONObject userInfo = new JSONObject(decodedValue);
                        return userInfo.getString(tokenName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
